import React, { Component } from 'react';
import ReactEcharts from 'echarts-for-react';
import axios from '../api'
import xyz from './xyz'

import echarts from 'echarts';

export default class DailyUser extends Component {
  constructor(props) {
    super(props);
    this.state = {
      option: {
        title: { text: '实时总人数：0人', textStyle: { fontSize: 12 }, right: 60 },
        xAxis: { type: 'time', name: '时间', nameTextStyle: { color: '#ffffff' } },
        yAxis: { type: 'value', name: '客流量(人)', nameTextStyle: { color: '#ffffff' } },
        grid: { top: 40, bottom: 40, left: 60, right: 60 },
        series: []
      }
    };
    this.seriesData = {}
  }

  componentWillMount () {
    echarts.registerTheme('xyz', xyz);
  }

  componentDidMount () {
    this.tick()
    this.timerID = setInterval(
      () => this.tick(),
      15 * 60 * 1000
    );
  }

  componentWillUnmount () {
    clearInterval(this.timerID);
  }

  tick () {
    axios.get('/daily_user').then(({ data: { data, total } }) => {
      this.genData(data, total)
    })

  }

  genData (data, total) {
    const { option } = this.state

    const genStyle = (color1, color2) => ({
      color: {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [{
          offset: 0, color: color2 // 0% 处的颜色
        }, {
          offset: 1, color: color1 // 100% 处的颜色
        }],
        globalCoord: false // 缺省为 false
      }
    })

    const colorList = [['#343491', '#C849ED'], ['#009EB5', '#55F9F6']]


    const series = data.map((item, idx) => ({
      name: item.name,
      type: 'line',
      smooth: true,
      symbol: 'roundRect',
      showSymbol: false,
      smoothMonotone: 'none',
      data: item.data,
      areaStyle: {
        opacity: 0.3,

      },
      itemStyle: idx < colorList.length ? genStyle(...colorList[idx]) : {}
    }))


    const title = {
      text: `实时总人数：${total}人`, textStyle: { fontSize: 12 }, right: 4
    }

    this.setState({ option: Object.assign({}, option, { series, title }) })
  }

  render () {
    return (
      <ReactEcharts
        option={this.state.option}
        notMerge={true}
        lazyUpdate={true}
        style={{ height: '100%' }}
        theme={'xyz'} />
    )
  }
}